package finn.movingheadtracker;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.ListModel;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;

import com.github.sarxos.webcam.Webcam;

public class Cameraviews implements ListModel<Cameraview>{
	public List<Cameraview> list;
	public int nextId;
	//Listeners
	List<ListDataListener> listeners = new ArrayList<ListDataListener>();
	public Cameraviews(){
		list = new ArrayList<Cameraview>();
	}
	/**
	 * Gets the next free id
	 * @return next Free id
	 */
	public int getNextId(){
		nextId++;
		return (nextId-1);
	}
	/* TODO Add exceptions
	 * 
	 */
	public void addPossible(){
		List<Webcam> cams = Webcam.getWebcams();
		for(Iterator<Webcam> it = cams.iterator(); it.hasNext();){
			Webcam cam=it.next();
			Cameraview view = new Cameraview();
			view.id = this.getNextId();
			view.name = cam.getName();
			view.res = new Dimension(320,320);
			view.setSource("webcam", cam.getName());
			list.add(view);
		}
	}

	public Cameraview getCameraview(int id){
		for(Iterator<Cameraview> it = list.iterator(); it.hasNext();){
			Cameraview view = it.next();
			if(id == view.id){
				return view;
			}
		}
		return null;
	}
	/**
	 * Get a Cameraview by a name
	 * @param name Format: "0 - Default Webcam"
	 * @return
	 */
	public Cameraview getCameraview(String name){
		return getCameraview(Integer.parseInt(name.split(" - ",2)[0]));
	}
	public void addElement(Cameraview view){
		list.add(view);
		int index = list.indexOf(view);
		for(ListDataListener listener : listeners){
			listener.intervalAdded(new ListDataEvent(view,ListDataEvent.CONTENTS_CHANGED,index,index));
		}
	}
	public void removeElement(Cameraview view){
		int index = list.indexOf(view);
		list.remove(view);
		for(ListDataListener listener : listeners){
			listener.intervalRemoved(new ListDataEvent(view,ListDataEvent.INTERVAL_REMOVED,index,index));
		}
	}
	public void updateElement(Cameraview oldview, Cameraview view){
		int oldindex = list.indexOf(oldview);
		list.remove(oldview);
		list.add(oldindex, view);
		for(ListDataListener listener : listeners){
			listener.contentsChanged(new ListDataEvent(view,ListDataEvent.CONTENTS_CHANGED,oldindex,oldindex));
		}
	}
	
	@Override
	public void addListDataListener(ListDataListener l) {
		listeners.add(l);
	}

	@Override
	public Cameraview getElementAt(int index) {
		return list.get(index);
	}

	@Override
	public int getSize() {
		return list.size();
	}

	@Override
	public void removeListDataListener(ListDataListener l) {
		listeners.remove(l);
		
	}
	public List<Cameraview> getList(){
		return list;
	}
}
